package cn.t222.service;

import cn.t222.mapper.SysRoleMapper;
import cn.t222.pojo.SysRole;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheConfig;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.List;
@Service
@CacheConfig(cacheNames = "role-service")
public class RoleService {
    @Resource
    private SysRoleMapper sysRoleMapper;
    @CacheEvict(allEntries = true)
    public int add(SysRole role) {
        return sysRoleMapper.add(role);
    }
    @CacheEvict(allEntries = true)
    public int del(Integer id) {
        return sysRoleMapper.del(id);
    }
    @CacheEvict(allEntries = true)
    public int update(SysRole role) {
        return sysRoleMapper.update(role);
    }
    public SysRole get(Integer id) {
        return sysRoleMapper.get(id);
    }

    @Cacheable(key = "targetClass + ':' + methodName")
    public List<SysRole> getAll() {
        return sysRoleMapper.getAll();
    }

    /**
     * 1.删除用户原有的角色
     * 2.给用户添加指定的角色（roleIds)
     * @param userId
     * @param roleIds
     */
    @Transactional
    @CacheEvict(allEntries = true)
    public void updateRoles(Integer userId, Integer[] roleIds) {
        sysRoleMapper.delUserRole(userId);
        for (Integer roleId: roleIds) {
            sysRoleMapper.addUserRole(userId, roleId);
        }

    }
}
